<!-- src/components/Rating.vue -->
<template>
  <div class="rating-component">
    <el-rate
      v-model="localRating"
      :max="max"
      :allow-half="allowHalf"
      :disabled="disabled"
      @change="handleChange"
    />
    <span v-if="showText" class="rating-text">{{ ratingText }}</span>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';

// 定义props
interface Props {
  modelValue?: number;
  max?: number;
  allowHalf?: boolean;
  disabled?: boolean;
  showText?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: 0,
  max: 5,
  allowHalf: false,
  disabled: false,
  showText: false
});

// 定义事件
const emit = defineEmits<{
  'update:modelValue': [value: number];
  'change': [value: number];
}>();

// 本地评分值
const localRating = ref(props.modelValue);

// 监听外部值变化
watch(() => props.modelValue, (newVal) => {
  localRating.value = newVal;
});

// 评分文本
const ratingText = computed(() => {
  const rating = localRating.value;
  if (rating === 0) return '未评分';
  if (rating < 2) return '很差';
  if (rating < 3) return '较差';
  if (rating < 4) return '还行';
  if (rating < 5) return '很好';
  return '极好';
});

// 处理评分变化
const handleChange = (value: number) => {
  localRating.value = value;
  emit('update:modelValue', value);
  emit('change', value);
};
</script>

<style scoped>
.rating-component {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.rating-text {
  margin-left: 0.5rem;
  color: #909399;
  font-size: 0.9rem;
}
</style>